<template>
  <div class="sub-category">
    <div class="title">{{ categories.category.name }}</div>
    <van-grid :gutter="10" :column-num="3">
      <van-grid-item
        v-for="category in categories.categories"
        :key="category.id"
        :icon="category.imageUrl"
        :text="category.title"
      />
    </van-grid>
  </div>
</template>

<script>
import { getSubCategories } from '@/api/category'
export default {
  name: 'SubCategory',
  data() {
    return {
      categories: []
    }
  },
  watch: {
    // 监听路由变化
    $route: {
      handler(newVal, oldVal) {
        console.log('路由变化了：', newVal.params.cid)
        // 根据父级分类 id 查询子分类
        getSubCategories(newVal.params.cid)
          .then((data) => {
            console.log(data)
            this.categories = data
          })
          .catch((err) => console.log('err:', err))
      },
      deep: true,
      immediate: true // 立即以表达式的当前值触发回调，handle函数
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  text-align: center;
  height: 80px;
  line-height: 100px;
  font-size: 16px;
  font-weight: 900;
  letter-spacing: 20px;
}
.van-grid {
  margin: 20px 0;
}
</style>
